package ch.kerbtier.malurus.coreimpl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import ch.kerbtier.malurus.Visitor;
import ch.kerbtier.malurus.Component;
import ch.kerbtier.malurus.CompositeComponent;

public class CiCompositeComponent extends CiComponent implements CompositeComponent {

	private int idCounter = 1;
	private Map<String, Component> children = new HashMap<String, Component>();
	private boolean changedStructure = false;

	@Override
	public boolean modified() {
		return super.modified() || changedStructure;
	}

	@Override
	protected void setInstance(CiMalurusInstance instance) {
		super.setInstance(instance);
		for (Component cic : this) {
			((CiComponent) cic).setInstance(instance);
		}
	}

	public void register(Component component) {
		String id = "i" + idCounter++;
		register(id, component);
	}

	public void register(String id, Component component) {
		CiComponent ci = (CiComponent) component;
		ci.setId(id);
		ci.setParent(this);
		ci.setInstance(getInstance());
		children.put(id, ci);
		if (ci.isVisible()) {
			changedStructure = true;
		}
	}

	public void unregister(Component component) {
		CiComponent removed = (CiComponent)children.remove(component.getId());
		if (removed != null) {
			removed.setParent(null);
			removed.setInstance(null);
			if (removed.isVisible()) {
				changedStructure = true;
			}
		}
	}

	public void setChangedStructure(boolean changedStructure) {
		this.changedStructure = changedStructure;
	}

	public Iterator<Component> iterator() {
		return children.values().iterator();
	}
	
	@Override
	public void acceptVisitor(Visitor visitor) {
		visitor.visit(this);
	}

}
